<template>
  <div class="tp-box">
    <a-drawer
      :visible="props.visible"
      :width="props.width"
      :closable="props.closable"
      :destroyOnClose="props.destroyOnClose"
      @close="handleClose"
    >
      <template #title>
        <div class="title-detail">
          <Tooltip placement="top">
            <template #title>
              <span>{{ getTipTitle }}</span>
            </template>
            <h3>{{ getTitle }}</h3>
          </Tooltip>
        </div>
      </template>
      <div>
        <a-space style="margin-left: 13px">
          <span>行政区划：</span>
          <a-input-group compact>
            <a-cascader
              v-model:value="strXzqm"
              style="width: 100%"
              :options="options1"
              expand-trigger="hover"
              placeholder="请选择行政区"
              changeOnSelect
            />
          </a-input-group>
        </a-space>
        <a-space style="margin-left: 10px">
          <span>开始时间：</span>
          <a-date-picker v-model:value="startDate" :format="dateFormat" />
        </a-space>
        <a-space style="margin-left: 10px">
          <span>结束时间：</span>
          <a-date-picker v-model:value="endDate" :format="dateFormat" />
        </a-space>
        <a-space style="width: 11%; margin-top: 15px; margin-left: 25px">
          <span>核验来源：</span>
          <a-select ref="select" v-model:value="role_type" style="width: 120px">
            <a-select-option value="4">乡镇</a-select-option>
            <a-select-option value="3">区级</a-select-option>
            <a-select-option value="2">市级</a-select-option>
          </a-select>
        </a-space>
        <a-space style="width: 17%; margin-top: 15px; margin-left: 5px">
          <span>关键字：</span>
          <a-input
            v-model:value="txtKeyWord"
            placeholder="请输入户主姓名、地址、房屋编号、核查人员姓名进行查询"
            style="width: 256px; margin-top: -10px"
          />
        </a-space>
        <a-space style="margin-top: 15px; margin-left: 15px">
          <a-form-item name="cs">
            <a-checkbox-group v-model:value="cs">
              <a-checkbox value="0">全部</a-checkbox>
              <a-checkbox value="1">一层</a-checkbox>
              <a-checkbox value="2">二层</a-checkbox>
              <a-checkbox value="3">三层</a-checkbox>
              <a-checkbox value="4">三层及以上</a-checkbox>
            </a-checkbox-group>
          </a-form-item>
        </a-space>
        &nbsp;&nbsp;&nbsp;&nbsp;
        <a-space class="search-btn">
          <a-button type="primary" @click="searchBtn">查询</a-button>
        </a-space>
        &nbsp;&nbsp;&nbsp;&nbsp;
        <a-space class="search-btn" style="float: right; margin-right: 10px">
          <a-button type="primary" @click="handleMxExport"> 导出明细表</a-button>
        </a-space>
      </div>

      <!-- :scroll="{ x: 1500, y: 600 }" -->
      <a-table
        :columns="computedTableColumn"
        :data-source="computedTableData"
        :page-size-options="pageSizeOptions"
        :loading="loading"
        bordered
        :pagination="false"
        size="middle"
        :scroll="{ x: 'calc(700px + 50%)', y: props.detailTableHeight }"
      >
        <!-- <template #action>
          <a>action</a>
        </template> -->
      </a-table>
      <div class="pagination">
        <a-pagination
          show-size-changer
          v-model:current="pageIndex"
          v-model:pageSize="pageSize"
          :total="total"
          @show-size-change="onShowSizeChange"
        />
      </div>
    </a-drawer>
  </div>
</template>
<script setup lang="ts">
  import { Tooltip } from 'ant-design-vue';
  import { useRouter } from 'vue-router';
  import { ref, computed, onMounted, watch } from 'vue';
  import { HcHourseList } from '/@/api/demo/api';
  import { useGlobSetting } from '/@/hooks/setting';
  import moment from 'moment';
  import dayjs from 'dayjs';
  import { useUserStore } from '/@/store/modules/user';
  import { downloadByUrl } from '/@/utils/file/download';
  import { useCheckStore } from '/@/store/modules/checkStore';
  const userStore = useUserStore();
  const router = useRouter();
  const globSetting = useGlobSetting();
  // 表格的 ref Dom名称
  const role_type = ref<string>('4');
  const txtKeyWord = ref<string>(''); //核验人员姓名
  const cs = ref<string>('0'); //层数
  const dateFormat = 'YYYY-MM-DD';
  const startDate = ref<any>(null); // 开始时间
  const endDate = ref<any>(null); // 结束时间
  const strXzqm = ref<string>('');
  const xzqdm = ref<string>('');
  let options1 = ref<any[]>([]);
  // 目标页面读取
  const store = useCheckStore();
  const { startTime, endTime, roletype, txtKey, xzq, fooler } = store.formData || {};
  // 默认传过来的值q
  const props = defineProps({
    visible: {
      type: Boolean,
      default: true,
    },
    title: {
      type: String,
      default: '',
    },
    width: {
      type: Number,
      default: 256,
    },
    detailTableHeight: {
      type: Number,
      default: 600,
    },
    hzfs: {
      type: String,
      default: '',
    },
    closable: {
      type: Boolean,
      default: true,
    },
    data: {
      type: Array,
      default: () => [],
    },
    detailParams: {
      type: Object,
      default: () => {},
    },
    currentXzqdmname: {
      type: String,
      default: '',
    },
    currentTitle: {
      type: String,
      default: '',
    },
    wscolsList: {
      type: Array,
      default: () => [{ wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }],
    },
    destroyOnClose: {
      type: Boolean,
      default: true,
    },
    onClose: {
      type: Function as PropType<() => void>,
      default: () => {},
    },
  });
  let pageIndex = ref(1);
  let pageSize = ref(25);
  let loading = ref(false);
  const pageSizeOptions = ref<string[]>(['100', '200', '300']);
  let tableSource = ref<any>([]);
  let total = ref(0);
  const columns = [
    { title: '序号', width: 50, dataIndex: 'index', key: 'index', align: 'center', fixed: 'left' },
    {
      title: '乡镇/街道',
      dataIndex: 'towndm',
      key: 'towndm',
      align: 'center',
      width: 170,
    },
    {
      title: '村名称',
      dataIndex: 'villagedm',
      key: 'villagedm',
      align: 'center',
      width: 150,
    },
    {
      title: '户主姓名',
      dataIndex: 'hzxm',
      key: 'hzxm',
      align: 'center',
      width: 150,
    },
    {
      title: '地址',
      dataIndex: 'address',
      key: 'address',
      align: 'center',
      width: 300,
    },
    {
      title: '层数',
      dataIndex: 'cs',
      key: 'cs',
      align: 'center',
      width: 100,
    },
    {
      title: '房屋编号',
      dataIndex: 'fwbh',
      key: 'fwbh',
      align: 'center',
      width: 170,
      customCell: (row, index, column) => {
        let isNoHzyh = row.town !== '汇总' ? true : false;
        let style = 'cursor:pointer;text-decoration: underline; color: blue;';
        let isNoZero = row[column.key] !== 0 ? true : false;
        return {
          style: `${isNoHzyh === true && isNoZero ? style : ''}`,
          class: 'cell-hover',
          onClick: async () => {
            getDetailData(row);
          },
        };
      },
    },
    {
      title: '核验人员姓名',
      dataIndex: 'nickname',
      key: 'nickname',
      align: 'center',
      width: 170,
    },
    {
      title: '核验时间',
      dataIndex: 'create_on',
      key: 'create_on',
      align: 'center',
      width: 170,
    },
    {
      title: '核验来源',
      dataIndex: 'yhly',
      key: 'yhly',
      align: 'center',
      width: 100,
    },
  ];

  // 计算总数的方法
  function vtotal(arr: any, item: any) {
    let total = arr.reduce((pre: any, cur: any) => {
      return parseInt(pre) + parseInt(cur[item]);
    }, 0);
    return total;
  }
  // 计算属性，用于实时更新数据到页面上
  const computedTableColumn = computed(() => {
    let newColumn: any = [];
    newColumn = columns;
    return newColumn;
  });
  const computedTableData = computed(() => {
    console.log(tableSource.value);
    return tableSource.value;
  });
  const getTitle = computed(() => {
    // let str = `【${props.currentXzqdmname} 】-- ${props.currentTitle}`;
    let str = `【${props.currentTitle}】`;
    if (str.length > 50) {
      str = str.substring(0, 50) + '...';
    }

    console.log('props.detailParams.startTime', roletype);
    if (startTime != null && startTime != '') {
      // eslint-disable-next-line vue/no-side-effects-in-computed-properties
      const sTime = moment(startTime).format('YYYY-MM-DD');
      const eTime = moment(endTime).format('YYYY-MM-DD');
      const start: any = dayjs(sTime);
      const end: any = dayjs(eTime);
      // eslint-disable-next-line vue/no-side-effects-in-computed-properties
      startDate.value = start;
      // eslint-disable-next-line vue/no-side-effects-in-computed-properties
      endDate.value = end;
    }

    // eslint-disable-next-line vue/no-side-effects-in-computed-properties
    role_type.value = roletype;
    // eslint-disable-next-line vue/no-side-effects-in-computed-properties
    txtKeyWord.value = txtKey;
    // eslint-disable-next-line vue/no-side-effects-in-computed-properties
    cs.value = fooler;
    // eslint-disable-next-line vue/no-side-effects-in-computed-properties
    xzqdm.value = xzq;
    return str;
  });
  const getTipTitle = computed(() => {
    let str = `${props.currentTitle}`;
    if (props.detailParams.startTime != null && props.detailParams.startTime != '') {
      // eslint-disable-next-line vue/no-side-effects-in-computed-properties
      const sTime = moment(props.detailParams.startTime).format('YYYY-MM-DD');
      const eTime = moment(props.detailParams.endTime).format('YYYY-MM-DD');
      const start: any = dayjs(sTime);
      const end: any = dayjs(eTime);
      // eslint-disable-next-line vue/no-side-effects-in-computed-properties
      startDate.value = start;
      // eslint-disable-next-line vue/no-side-effects-in-computed-properties
      endDate.value = end;
    }

    // eslint-disable-next-line vue/no-side-effects-in-computed-properties
    role_type.value = props.detailParams.roletype;
    // eslint-disable-next-line vue/no-side-effects-in-computed-properties
    txtKeyWord.value = props.detailParams.txtKeyWord;
    // eslint-disable-next-line vue/no-side-effects-in-computed-properties
    cs.value = props.detailParams.cs;
    return str;
  });
  watch(
    () => props.visible,
    (newVal, oldVal) => {
      // console.log(`visible 变化了，新值：${newVal}，旧值：${oldVal}`);
      // 在这里执行你需要的操作
      if (newVal) {
        getTableData();
      }
    },
  );
  const getTableData = async () => {
    let params: any = {
      pageindex: pageIndex.value,
      pagesize: pageSize.value,
      startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
      endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
      roletype: role_type.value,
      txtKeyWord: txtKeyWord.value,
      filed: props.detailParams.filed,
      xzqdm:xzq
    };
    if (strXzqm.value != undefined) {
      params.xzqdm = strXzqm.value[0];
      params.towndm = strXzqm.value[1];
      params.villagedm = strXzqm.value[2];
    }
    loading.value = true;
    let res = await HcHourseList(params);
    loading.value = false;
    let zcount = vtotal(res.items, 'zcount');
    let hccount = vtotal(res.items, 'hccount');
    let hcl = Math.round(parseFloat((hccount / zcount) * 100)).toFixed(2) + '%';
    let 合计_count = '汇总';
    let yhcount = vtotal(res.items, 'yhcount');
    let zgcount = vtotal(res.items, 'zgcount');

    let wzgcount = vtotal(res.items, 'syyhcount');
    let yhccount = vtotal(res.items, 'yhccount');
    let whccount = vtotal(res.items, 'whccount');
    let ydbcount = vtotal(res.items, 'ydbcount');
    let wdbcount = vtotal(res.items, 'wdbcount');
    let dbl = Math.round(parseFloat((ydbcount / hccount) * 100)).toFixed(2) + '%';
    let tallObj = {
      xzq: 合计_count,
      zcount: zcount,
      hccount: hccount,
      hcl: hcl,
      yhcount: yhcount,
      zgcount: zgcount,
      whccount: whccount,
      syyhcount: wzgcount,
      wdbcount: wdbcount,
      ydbcount: ydbcount,
      dbl: dbl,
      yhccount: yhccount,
    };

    let list = res.items;
    tableSource.value = list;
    tableSource.value.push(tallObj);
    total.value = res.total;

    // console.log('@resqqq', list);
  };
  //  调用 父组件传过来的方法
  const emit = defineEmits(['close']);
  //跳转记录页面
  function getDetailData(row: any) {
    router.push({
      path: '/utils/houseCheckLog',
      query: {
        xzqdm: row.xzqdm,
        towndm: row.town,
        villagedm: row.village,
        hzxm: row.hzxm,
        fwbh: row.fwbh,
      },
    });
  }
  function searchBtn() {
    loading.value = true;
    getTableData();
  }
  function handleMxExport() {
    const uriBase = `${globSetting.apiBaseUrl}${globSetting.apiUrl}`;
    const tk = userStore.getToken;
    let xzqdm = '';
    let towndm = '';
    let villagedm = '';
    if (strXzqm.value[0] != undefined) {
      xzqdm = strXzqm.value[0];
    }
    if (strXzqm.value[1] != undefined) {
      towndm = strXzqm.value[1];
    }
    if (strXzqm.value[2] != undefined) {
      villagedm = strXzqm.value[2];
    }
    downloadByUrl({
      url:
        uriBase +
        '/export/hymx/exporthymx?access_token=' +
        tk +
        '&yhly=' +
        role_type.value +
        '&xzqdm=' +
        xzqdm +
        '&towndm=' +
        towndm +
        '&villagedm=' +
        villagedm +
        '&startTime=' +
        startDate.value.format('YYYY-MM-DD') +
        '&endTime=' +
        endDate.value.format('YYYY-MM-DD'),
      target: '_blank',
    });
  }

  const handleClose = () => {
    emit('close');
    pageIndex.value = 1;
    pageSize.value = 15;
  };
  // 切换页码的时候更新  pageIndex 和  pageSize
  const onShowSizeChange = (pageIndex: number, pageSize: number) => {
    // antDesign  自动给  pageIndex 和 pageSize 赋值
    // pageIndex.value = pageIndex;
    // pageSize.value = pageSize;
    // console.log('@pageIndex,pageSize', pageIndex, pageSize);
  };
  watch(pageSize, () => {
    // console.log('pageSize', pageSize.value);
    getTableData();
  });
  watch(pageIndex, () => {
    // console.log('current', pageIndex.value);
    getTableData();
  });
  onMounted(() => {
    getTableData();
  });
</script>
<style lang="less" scoped>
  .tp-box {
    height: 100%;
  }
  .title-detail {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
  }
  .pagination {
    margin-top: 5px;
    display: flex;
    justify-content: flex-end;
  }

</style>
<style>
  .ant-drawer-body {
    padding: 10px 24px !important;
  }
</style>